<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'shop:order:soOrderChg:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="85%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #soOrderChgCList>
        <BasicTable @register="registerSoOrderChgCTable" @row-click="handleSoOrderChgCRowClick">
          <template #cmemoOld="{ record }">
            <span :style="{ color: record.cmemoChange ? 'red' : '' }">{{ record.cmemoOld }}</span>
          </template>
          <template #remarksOld="{ record }">
            <span :style="{ color: record.remarksChange ? 'red' : '' }">{{
              record.remarksOld
            }}</span>
          </template>
        </BasicTable>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="soOrder"
        completeText="提交"
        :loading="loadingRef"
        :auth="'shop:order:soOrderChg:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderSoOrderChgForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { SoOrderChg, soOrderChgSave, soOrderChgForm } from '/@/api/shop/order/soOrderChg';
  import { BpmButton } from '/@/components/Bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop.order.soOrderChg');
  const { showMessage } = useMessage();
  const record = ref<SoOrderChg>({} as SoOrderChg);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('订单信息变更'),
  }));

  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('订单号'),
      field: 'soCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      required: true,
      labelWidth: 76,
    },
    {
      label: t('客户编码'),
      field: 'cusCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
      colProps: { lg: 12, md: 12 },
      labelWidth: 90,
    },
    {
      label: t('客户名称'),
      field: 'basCus.name',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      required: true,
      colProps: { lg: 12, md: 12 },
      labelWidth: 90,
    },
    {
      label: t('首批发货（修改前）'),
      field: 'bspOld',
      component: 'Select',
      componentProps: {
        dictType: 'bus_is_first',
        maxlength: 64,
      },
      dynamicDisabled: true,
      colProps: { lg: 12, md: 12 },
      labelWidth: 150,
    },
    {
      label: t('首批发货（修改后）'),
      field: 'bsp',
      component: 'Select',
      componentProps: {
        dictType: 'bus_is_first',
        maxlength: 64,
      },
      required: false,
      colProps: { lg: 12, md: 12 },
      labelWidth: 150,
    },
    {
      label: t('是否包邮（修改前）'),
      field: 'bbyOld',
      component: 'Select',
      componentProps: {
        dictType: 'bus_is_free',
        maxlength: 64,
      },
      dynamicDisabled: true,
      colProps: { lg: 12, md: 12 },
      labelWidth: 150,
    },
    {
      label: t('是否包邮（修改后）'),
      field: 'bby',
      component: 'Select',
      componentProps: {
        dictType: 'bus_is_free',
        maxlength: 64,
      },
      required: false,
      colProps: { lg: 12, md: 12 },
      labelWidth: 150,
    },
    {
      label: t('备注信息（修改前）'),
      field: 'cmemoOld',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
      colProps: { lg: 12, md: 12 },
      labelWidth: 150,
    },
    {
      label: t('备注信息（修改后）'),
      field: 'cmemo',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 255,
      },
      colProps: { lg: 12, md: 12 },
      labelWidth: 150,
    },
    {
      label: t('修改原因'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
      labelWidth: 80,
    },
    {
      label: t('订单明细'),
      field: 'soOrderChgCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'soOrderChgCList',
      labelWidth: 80,
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 150,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerSoOrderChgCTable, soOrderChgCTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleSoOrderChgCDelete.bind(this, record),
    //       },
    //       auth: 'shop:order:soOrderChg:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setSoOrderChgCTableData(_res: Recordable) {
    soOrderChgCTable.setColumns([
      {
        title: t('来源ID'),
        dataIndex: 'sourceId',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('行号'),
        dataIndex: 'soRds.irowno',
        width: 60,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('存货编码'),
        dataIndex: 'soRds.basInv.cinvcode',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('存货名称'),
        dataIndex: 'soRds.basInv.cinvname',
        width: 180,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('数量'),
        dataIndex: 'soRds.iquantity',
        width: 50,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('件数'),
        dataIndex: 'soRds.inum',
        width: 50,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('单价'),
        dataIndex: 'soRds.itaxunitprice',
        width: 50,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('金额'),
        dataIndex: 'soRds.isum',
        width: 50,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },

      {
        title: t('选项备注(修改前)'),
        dataIndex: 'cmemoOld',
        width: 180,
        align: 'left',
        dictType: 'btdm_order_memo_type',
        // editRow: true,
        // editComponent: 'Select',
        // editComponentProps: {
        //   dictType: 'btdm_order_memo_type',
        //   maxlength: 255,
        // },
        // editRule: false,
        // ifShow: false,
        slot: 'cmemoOld',
      },
      {
        title: t('选项备注(修改后)'),
        dataIndex: 'cmemo',
        width: 180,
        align: 'left',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'btdm_order_memo_type',
          maxlength: 255,
        },
        editRule: false,
        editable: true,
      },
      {
        title: t('备注信息(修改前)'),
        dataIndex: 'remarksOld',
        width: 180,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 255,
        // },
        // editRule: false,
        // ifShow: false,
        slot: 'remarksOld',
      },
      {
        title: t('备注信息(修改后)'),
        dataIndex: 'remarks',
        width: 180,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
        editable: true,
      },
    ]);
    soOrderChgCTable.setTableData(record.value.soOrderChgCList || []);
  }

  function handleSoOrderChgCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleSoOrderChgCAdd() {
    soOrderChgCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleSoOrderChgCDelete(record: Recordable) {
    soOrderChgCTable.deleteTableDataRecord(record);
  }

  async function getSoOrderChgCList() {
    let soOrderChgCListValid = true;
    let soOrderChgCList: Recordable[] = [];
    for (const record of soOrderChgCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        soOrderChgCListValid = false;
      }
      soOrderChgCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of soOrderChgCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      soOrderChgCList.push({
        ...record,
        status: '1',
      });
    }
    if (!soOrderChgCListValid) {
      throw { errorFields: [{ name: ['soOrderChgCList'] }] };
    }
    return soOrderChgCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await soOrderChgForm(data);
    record.value = (res.soOrderChg || {}) as SoOrderChg;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setSoOrderChgCTableData(res);
    // updateSchema([
    //   {
    //     field: 'cmemo',
    //     componentProps: { disabled: true },
    //   },
    // ]);
    setDrawerProps({ loading: false });
    if (record.value.bspChange) {
      // document.getElementById('bspOld').style.color = 'red';
      // document.getElementById('bsp').style.color = 'red';
      document.querySelector('.ant-col-md-12 #bspOld').style.color = 'red';
      document.querySelector('.ant-col-md-12 #bsp').style.color = 'red';
    }
    if (record.value.bbyChange) {
      // document.getElementById('bbyOld').style.color = 'red';
      // document.getElementById('bby').style.color = 'red';
      document.querySelector('.ant-col-md-12 #bbyOld').style.color = 'red';
      document.querySelector('.ant-col-md-12 #bby').style.color = 'red';
    }
    if (record.value.cmemoChange) {
      // document.getElementById('cmemoOld').style.color = 'red';
      // document.getElementById('cmemo').style.color = 'red';
      document.querySelector('.ant-col-md-12 #cmemoOld').style.color = 'red';
      document.querySelector('.ant-col-md-12 #cmemo').style.color = 'red';
    }
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.soOrderChgCList = await getSoOrderChgCList();
      // console.log('submit', params, data, record);
      const res = await soOrderChgSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }
  .jeesite-editable-cell__action {
    display: none;
  }

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
  :deep(#sumMoneyLmit) {
    color: red;
  }
  :deep(#form_item_sumMoneyLmit) {
    color: red !important;
  }
</style>
